package wechat.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import wechat.bean.WechatInformationBean;
import wechat.entity.AccessTokenEntity;
import wechat.entity.JSTicketEntity;
import wechat.resources.AppFilter;
import wechat.resources.InstanceResource;
import wechat.service.impl.IAccessTokenService;
import wechat.service.impl.IAuthService;
import wechat.service.impl.IJSTicketService;
import wechat.service.impl.IWechatInfoService;
import wechat.util.aes.AesException;
import wechat.util.aes.WXBizMsgCrypt;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Controller
@RequestMapping("/ryt")
public class WechatController {

	private Logger log = LoggerFactory.getLogger(WechatController.class);	
	
	@Autowired
	private IWechatInfoService wechatInfoService;
	@Autowired
	private IAuthService  authService;
	
	
	@Autowired
	IAccessTokenService accessTokenService;
	@Autowired
	IJSTicketService jsTicketService;
	
	@RequestMapping(value = "/{appid}",method = RequestMethod.GET)
	@ResponseBody
	public String confirmation(HttpServletRequest request,
							   @PathVariable(value = "appid") String appid,
							   @RequestParam(value = "msg_signature") String signature,
							   @RequestParam(value = "timestamp") String timestamp, 
							   @RequestParam(value = "nonce") String nonce,
							   @RequestParam(value = "echostr") String echostr) {

		log.info("WechatController -- confirmation appid=" + appid + " signature=" + signature + " timestamp=" + timestamp + " nonce=" + nonce + " echostr=" + echostr);
	
		if (signature == null && timestamp == null && nonce == null) {
			log.error("WechatController -- confirmation wxBizMsgCrypt param is null");
			return "";
		}
		
		InstanceResource instanceResource = AppFilter.chooseApp(appid);
		WXBizMsgCrypt wxBizMsgCrypt;
		try {
			wxBizMsgCrypt = instanceResource.getWXBizMsgCrypt();
			String checkStr = wxBizMsgCrypt.verifyUrl(signature, timestamp, nonce, echostr);
			log.info("WechatController -- confirmation checkStr=" + checkStr);
			
			return checkStr;
		} catch (AesException e) {
			log.error("WechatController -- confirmation: 服务器验证失败！",e);
			e.printStackTrace();
		}
	
		return "";
	}
	

	@RequestMapping(value = "/{appid}",method = RequestMethod.POST)
	@ResponseBody
	public String message(HttpServletRequest request,
						  @PathVariable(value = "appid") String appid,
						  @RequestParam(value = "msg_signature") String signature,
						  @RequestParam(value = "timestamp") String timestamp, 
					 	  @RequestParam(value = "nonce") String nonce) {
		log.info("WechatController -- message  appid=" + appid + " signature=" + signature + " timestamp=" + timestamp + " nonce=" + nonce);
	
		if (signature == null && timestamp == null && nonce == null) {
			log.error("WechatController -- message wxBizMsgCrypt param is null");
			return "";
		}
		
		InstanceResource instanceResource = AppFilter.chooseApp(appid);
		WechatInformationBean wechatInformationBean = new WechatInformationBean();

		InputStream dataInputStream = null;
		
		try {
			dataInputStream = request.getInputStream();

			wechatInformationBean.setDataInputStream(dataInputStream);
			wechatInformationBean.setMsgSignature(signature);
			wechatInformationBean.setNonce(nonce);
			wechatInformationBean.setTimestamp(timestamp);
		} catch (IOException e) {
			log.error("WechatController -- message  获取数据失败",e);
			e.printStackTrace();
		}
		
		
		String result = wechatInfoService.doWechatInfo(instanceResource, wechatInformationBean);
//		System.out.println(wechatInfoService.findMessage());
//		System.out.println("--------------------------------");
//		System.out.println(wechatInfoService.findEvent());
		return result;
	}
	
	
	
	@RequestMapping(value = "/auth/{appid}",method = RequestMethod.GET)
	@ResponseBody
	public void auth(HttpServletRequest request,
						  @PathVariable(value = "appid") String appid,
						  @RequestParam(value = "code") String code,
						  @RequestParam(value = "state") String state) {

		log.info("WechatController -- auth  appid=" + appid + " code=" + code + " state=" + state);

		InstanceResource instanceResource = AppFilter.chooseApp(appid);
		String userid = "";
		try {
			 userid = authService.getUserId(instanceResource, code);
			log.info("WechatController -- auth  userid=" + userid);		
			
//			String openid = authService.getOpenidByUserid(instanceResource, userid, "53");
//			String openid2 = authService.getOpenidByUserid(instanceResource, userid, null);
//			System.out.println(openid + "------"+ openid2);
		} catch (Exception e) {
			log.error("WechatController -- auth  获取授权失败",e);
			e.printStackTrace();
		}
		
		//return userid;
	}
	

	
	@RequestMapping(value = "/preService/{appid}")
	@ResponseBody
	public void preMenu(HttpServletRequest request,HttpServletResponse response,
						  @PathVariable(value = "appid") String appid,
						  @RequestParam(value = "state") String state) throws IOException {

		log.info("WechatController -- preMenu  appid=" + appid + " state=" + state);
		
		InstanceResource instanceResource = AppFilter.chooseApp(appid);
		String url = "";
		try {
			url = authService.getOauth2URL(instanceResource, state);
		} catch (Exception e) {
			log.error("WechatController -- preMenu  获取授权失败",e);
			e.printStackTrace();
		}

		
//		try {
//			//AccessTokenEntity entity = accessTokenService.getAccessToken(appid);
//			JSTicketEntity entity = jsTicketService.getJSTicket(appid);
//			log.info("WechatController -- preMenu entity=" + entity);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
		
		response.sendRedirect(url);
	}
}
